<?php

declare(strict_types=1);

namespace Yolo\Commands;

use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Input\InputOption;
use Yolo\Config\ConfigManager;
use Yolo\IdGenerator\Uuid;

#[Command]
class CreateUuid extends HyperfCommand
{
    public function __construct(protected ContainerInterface $container)
    {
        parent::__construct('uuid:new');
    }

    public function configure(): void
    {
        parent::configure();
        $this->setDescription('Create a new uuid');
        $this->addOption('override', null, InputOption::VALUE_NONE, 'Whether to overwrite the configuration file.');
    }

    public function handle(): void
    {
        $uuid = (new Uuid())->generateId();

        $override = $this->input->getOption('override');

        if ($override) {
            try {
                $this->writeUuidToConfig($uuid);
                $this->line("Application.instanceId updated: $uuid", 'info');
            } catch (\Exception $e) {
                $this->line($e->getMessage(), 'error');
                $this->line("Application config has restored.", 'info');
            }
        } else {
            $this->line($uuid, 'info');
        }
    }

    private function writeUuidToConfig(string $uuid): void
    {
        $configMrg = new ConfigManager(BASE_PATH);
        $config = $configMrg->getConfig();

        $config['application']['instanceId'] = $uuid;

        $configMrg->updateConfig($config);
        $configMrg->saveConfig();
    }
}
